import Vuex from "vuex";
import {createStore} from "vuex";

const setLocalCartList = (state) => {
    const { cartList } = state
    const cartListString = JSON.stringify(cartList)
    localStorage.cartList = cartListString
}

const getLocalCartList = () => {
    let val = localStorage.cartList||'[]';
    val = JSON.parse(val).filter(n => n)
    return val
}

//第一层级 商铺id
//第二层级 id是商品id，内容是商品内容及购物数量
// shopId:{
//     shopName:"沃尔玛"
//     productList:{
//         _id:'1',
//         check:ture,
//         name:'番茄250g/份',
//         imgUrl:'http://www.dell-lee.com/imgs/vue3/tomato.png',
//         sales:'10',
//         price:'33.6',
//         oldprice:'39.6',
//         count: 1
//     }
// }
export default Vuex.createStore({
    state: {
        cartList: getLocalCartList()
    },
    mutations: {
        changeCartItemInfo(state, payload){
            const {shopId, productId, productInfo, num} = payload
            let shopInfo = state.cartList[shopId] || {
                shopName: '', productList:{}
            }
            let product = shopInfo.productList[productId]
            if(!product) {
                productInfo.count = 0
                product=productInfo
            }
            product.count = product.count + payload.num
            payload.num > 0 && (product.check = true)
            product.count<0 && (product.count = 0)
            shopInfo.productList[productId] = product
            state.cartList[shopId] = shopInfo
            setLocalCartList(state)
        },
        changeCartItemChecked(state, payload){
            const {shopId, productId} = payload
            const product = state.cartList[shopId].productList[productId]
            product.check = !product.check
            setLocalCartList(state)
        },
        clearCartProducts(state, payload){
            const {shopId} = payload
            state.cartList[shopId].productList = {}
            setLocalCartList(state)
        },
        setCartItemsChecked(state, payload){
            const {shopId} = payload
            const products = state.cartList[shopId].productList
            if(products){
                for(let i in products){
                    const product = products[i]
                    product.check = true
                }
            }
            setLocalCartList(state)
        },
        changeShopName(state, payload){
            const {shopId, shopName} = payload
            const shopInfo = state.cartList[shopId] || {
                shopName: '', productList:{}
            }
            shopInfo.shopName = shopName
            state.cartList[shopId] = shopInfo
            setLocalCartList(state)
        }
    },
    actions: {},
    modules: {}
})
